package com.glitech.demo.data;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Database(entities = {VoiceCmd.class}, version = 1, exportSchema = false)
public abstract class VoiceCmdRoomDatabase extends RoomDatabase {
    public abstract VoiceCmdDao voiceCmdDao();

    private static VoiceCmdRoomDatabase INSTANCE;
    private static final int NUM_OF_THREADS = 4;
    public static final ExecutorService databaseWriteExecutor =
            Executors.newFixedThreadPool(NUM_OF_THREADS);

    public static VoiceCmdRoomDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (VoiceCmdRoomDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            VoiceCmdRoomDatabase.class, "word_database")
                            .addCallback(sRoomDatabaseCallback).allowMainThreadQueries()
                            .build();
                }
            }
        }
        return INSTANCE;
    }


    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            databaseWriteExecutor.execute(() -> {
                VoiceCmdDao dao = INSTANCE.voiceCmdDao();
                dao.deleteAll();
            });
        }
    };

}
